import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router from '../../router'
import Layout from '../../views/layout/Layout'

const user = {
  state: {
    token: getToken(),
    name: '',
    roles: '',
    id: '',
    num: '0'
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NUM: (state, num) => {
      state.num = num
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim()
      let hour = 2
      if (userInfo.remember) {
        hour = 7 * 24
      }
      return new Promise((resolve, reject) => {
        login(username, userInfo.password, userInfo.remember).then(response => {
          const token = response.result
          setToken(token, hour)
          commit('SET_TOKEN', token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo(state.token).then(response => {
          const data = response.result
          if (data.roles && data.roles.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_ROLES', data.roles)
          } else {
            reject('getInfo: roles must be a non-null array !')
          }
          // 1.生成路由
          let menus = []
          if (data.roles === '0') {
            // 管理员菜单
            menus = [{
              path: '/admin/index',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '首页',
                  component: () => import('@/views/admin/index/index'),
                  meta: { title: '首页', icon: 'home' }
                }
              ]
            }, {
              path: '/admin/group',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '小组管理',
                  component: () => import('@/views/admin/group/list'),
                  meta: { title: '小组管理', icon: 'group' }
                }
              ]
            }, {
              path: '/admin/student',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '学生管理',
                  component: () => import('@/views/admin/student/list'),
                  meta: { title: '学生管理', icon: 'student' }
                }
              ]
            }, {
              path: '/admin/teacher',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '教师管理',
                  component: () => import('@/views/admin/teacher/list'),
                  meta: { title: '教师管理', icon: 'teacher' }
                }
              ]
            }, {
              path: '/admin/class',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '班级管理',
                  component: () => import('@/views/admin/class/list'),
                  meta: { title: '班级管理', icon: 'class' }
                }
              ]
            }, {
              path: '/admin',
              component: Layout,
              name: '帮助文档',
              meta: { title: '帮助文档', icon: 'help' },
              children: [
                {
                  path: '/admin/help/student',
                  name: '导入学生',
                  component: () => import('@/views/admin/help/student'),
                  meta: { title: '导入学生', icon: 'student' }
                },
                {
                  path: '/admin/help/teacher',
                  name: '导入教师',
                  component: () => import('@/views/admin/help/teacher'),
                  meta: { title: '导入教师', icon: 'teacher' }
                }
              ]
            }, {
              path: '*',
              redirect: '/404',
              hidden: true
            }]
          } else if (data.roles === '1') {
            // 教师端菜单
            menus = [{
              path: '/teacher/index',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '首页',
                  component: () => import('@/views/teacher/index/index'),
                  meta: { title: '首页', icon: 'home' }
                }
              ]
            }, {
              path: '/teacher/message',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '消息列表',
                  component: () => import('@/views/teacher/message/index'),
                  meta: { title: '消息列表', icon: 'message' }
                }
              ]
            }, {
              path: '/teacher/reply',
              component: Layout,
              hidden: true,
              children: [
                {
                  path: '',
                  name: '答辩详情',
                  component: () => import('@/views/teacher/reply/info'),
                  meta: { title: '答辩详情', icon: 'reply' }
                }
              ]
            }, {
              path: '/teacher/list',
              component: Layout,
              hidden: true,
              children: [
                {
                  path: '',
                  name: '答辩列表',
                  component: () => import('@/views/teacher/reply/list'),
                  meta: { title: '答辩列表', icon: 'list' }
                }
              ]
            }, {
              path: '/teacher/analyse',
              component: Layout,
              hidden: true,
              children: [
                {
                  path: '',
                  name: '答辩分析',
                  component: () => import('@/views/teacher/reply/analyse'),
                  meta: { title: '答辩分析', icon: 'analyse' }
                }
              ]
            }, {
              path: '/teacher/info',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '个人信息',
                  component: () => import('@/views/teacher/info/index'),
                  meta: { title: '个人信息', icon: 'info' }
                }
              ]
            }, {
              path: '*',
              redirect: '/404',
              hidden: true
            }]
          } else {
            // 学生端菜单
            menus = [{
              path: '/student/index',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '首页',
                  component: () => import('@/views/student/index/index'),
                  meta: { title: '首页', icon: 'home' }
                }
              ]
            }, {
              path: '/student/message',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '消息列表',
                  component: () => import('@/views/student/message/index'),
                  meta: { title: '消息列表', icon: 'message' }
                }
              ]
            }, {
              path: '/student/reply',
              component: Layout,
              hidden: true,
              children: [
                {
                  path: '',
                  name: '答辩详情',
                  component: () => import('@/views/student/reply/info'),
                  meta: { title: '答辩详情', icon: 'reply' }
                }
              ]
            }, {
              path: '/student/grade',
              component: Layout,
              hidden: true,
              children: [
                {
                  path: '',
                  name: '我的成绩',
                  component: () => import('@/views/student/reply/grade'),
                  meta: { title: '我的成绩', icon: 'grade' }
                }
              ]
            }, {
              path: '/student/analyse',
              component: Layout,
              hidden: true,
              children: [
                {
                  path: '',
                  name: '答辩分析',
                  component: () => import('@/views/student/reply/analyse'),
                  meta: { title: '答辩分析', icon: 'analyse' }
                }
              ]
            }, {
              path: '/student/info',
              component: Layout,
              children: [
                {
                  path: '',
                  name: '个人信息',
                  component: () => import('@/views/student/info/index'),
                  meta: { title: '个人信息', icon: 'info' }
                }
              ]
            }, {
              path: '*',
              redirect: '/404',
              hidden: true
            }]
          }
          router.addRoutes(menus) // 2.动态添加路由
          global.antRouter = menus // 3.将路由数据传递给全局变量，做侧边栏菜单渲染工作
          commit('SET_NAME', data.name)
          commit('SET_ID', data.id)
          commit('SET_NUM', data.num)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_TOKEN', '')
          commit('SET_ROLES', [])
          commit('SET_NAME', '')
          commit('SET_ID', '')
          commit('SET_NUM', '0')
          removeToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        removeToken()
        resolve()
      })
    },

    // 前端增加未读消息数
    IncreaseMsgNum({ commit, state }) {
      const msgNum = state.num
      const newNum = parseInt(msgNum) + 1
      commit('SET_NUM', newNum + '')
    },

    // 前端减少未读消息数
    ReduceMsgNum({ commit, state }) {
      const msgNum = state.num
      const newNum = parseInt(msgNum) - 1
      commit('SET_NUM', newNum + '')
    }
  }
}

export default user
